package com.assist.common.utils;

import cn.hutool.poi.excel.WorkbookUtil;
import com.assist.common.entity.common.ExcelProtoEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by wuqiang on 2022/8/27 15:51
 */

public class ReadProtoUtil {

    public static void main(String[] args) throws IOException {
        String filePath = "D:\\gxworkspace\\ib_service\\proto\\ib\\accesscontrol";
//        String filePath = "D:\\gxworkspace\\ib_service\\proto\\ib\\elemac\\v1";
        List<String> files = traverseFolder(filePath, ".proto");
        action(files);
    }

    public static void action(List<String> files) throws IOException {
        List<ExcelProtoEntity> results = new LinkedList<>();
        for (String file : files) {
            BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(new File(file)), "UTF-8"));
            String lastLine = "";
            String currentLine = "";

            ExcelProtoEntity.TableRowReq tableRowReq = null;
            ExcelProtoEntity excelProtoEntity = null;
            boolean isRead = false;
            while ((currentLine = bf.readLine()) != null) {
                currentLine = currentLine.trim();
                if (currentLine.contains("message ")) {
                    excelProtoEntity = new ExcelProtoEntity();
                    String[] methods = currentLine.split(" ");
                    if(methods.length == 3){
                        excelProtoEntity.setReqDesc(methods[1].trim());
                    }
//                    if (lastLine.length() > 2 && lastLine.contains("//")) {
//                        excelProtoEntity.setReqDesc(lastLine.trim().substring(2));
//                    }
                    isRead = true;
                }
                if (isRead && !currentLine.equals("message ")
                        && !currentLine.contains("//") && !currentLine.contains("}")
                        && !currentLine.contains("{")) { tableRowReq = excelProtoEntity.new TableRowReq();
                    tableRowReq.setFieldDesc(getFileDesc(lastLine));
                    tableRowReq.setFieldName(getFileName(currentLine));
                    tableRowReq.setFieldType(getFileType(currentLine));

                    List<ExcelProtoEntity.TableRowReq> tableRowReqs = excelProtoEntity.getTableRowReqs();
                    if (tableRowReqs == null) {
                        tableRowReqs = new LinkedList<>();
                        tableRowReqs.add(tableRowReq);
                        excelProtoEntity.setTableRowReqs(tableRowReqs);
                    } else {
                        tableRowReqs.add(tableRowReq);
                    }
                }
                if (currentLine.contains("}") && excelProtoEntity != null) {
                    results.add(excelProtoEntity);
                }
                if (currentLine.contains("}")) {
                    isRead = false;
                }
                lastLine = currentLine;
            }
        }
        exportExcel(results);
    }

    private static void exportExcel(List<ExcelProtoEntity> entitys) throws IOException {
        Workbook workbook = WorkbookUtil.createBook(true);
        workbook.createSheet("自动生成proto对象");
        Sheet sheet = workbook.getSheetAt(0);
        setExcelData(sheet, entitys);
        FileOutputStream fos = new FileOutputStream("D://proto转实体类.xlsx");
        workbook.write(fos);
        fos.close();
        workbook.close();
        System.out.println("导出excel成功");
    }

    /**
     * 设置填写值
     */
    private static void setExcelData(Sheet sheet, List<ExcelProtoEntity> entitys) {
        //建立表头
        int startRow = 0;
        for (int i = 0; i < entitys.size(); i++) {
            ExcelProtoEntity excelProtoEntity = entitys.get(i);
            Row descRow = sheet.createRow(startRow);
            descRow.createCell(0).setCellValue(excelProtoEntity.getReqDesc());
            startRow += 1;
            Row title = sheet.createRow(startRow);
            title.createCell(0).setCellValue("字段");
            title.createCell(1).setCellValue("类型");
            title.createCell(2).setCellValue("说明");
            if (excelProtoEntity.getTableRowReqs() == null || excelProtoEntity.getTableRowReqs().size() < 1) {
                continue;
            }
            startRow += 1;
            for (int j = 1; j <= excelProtoEntity.getTableRowReqs().size(); j++) {
                Row row = sheet.createRow(startRow);
                ExcelProtoEntity.TableRowReq tableRowReq = excelProtoEntity.getTableRowReqs().get(j - 1);
                row.createCell(0).setCellValue(tableRowReq.getFieldName());
                row.createCell(1).setCellValue(tableRowReq.getFieldType());
                row.createCell(2).setCellValue(tableRowReq.getFieldDesc());
                startRow += 1;
            }
            startRow += 1;
        }
    }

    /**
     * 获取所有的文件
     *
     * @param path
     */
    public static List<String> traverseFolder(String path, String fileType) {
        int fileNum = 0, folderNum = 0;
        File file = new File(path);
        List<String> results = new ArrayList<>();
        if (file.exists()) {
            LinkedList<File> list = new LinkedList<>();
            File[] files = file.listFiles();
            for (File file2 : files) {
                if (file2.isDirectory()) {
//                    System.out.println("文件夹:" + file2.getAbsolutePath());
                    if (!file2.getAbsolutePath().contains("google")) {
                        list.add(file2);
                        folderNum++;
                    }
                } else {
                    if (StringUtils.isNotBlank(fileType)) {
                        if (file2.getAbsolutePath().contains(fileType)) {
                            results.add(file2.getAbsolutePath());
                        }
                    } else {
                        results.add(file2.getAbsolutePath());
                    }
//                    System.out.println("文件:" + file2.getAbsolutePath());
                    fileNum++;
                }
            }
            File temp_file;
            while (!list.isEmpty()) {
                temp_file = list.removeFirst();
                files = temp_file.listFiles();
                for (File file2 : files) {
                    if (file2.isDirectory()) {
//                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        list.add(file2);
                        folderNum++;
                    } else {
                        if (StringUtils.isNotBlank(fileType)) {
                            if (file2.getAbsolutePath().contains(fileType)) {
                                results.add(file2.getAbsolutePath());
                            }
                        } else {
                            results.add(file2.getAbsolutePath());
                        }
//                        System.out.println("文件:" + file2.getAbsolutePath());
                        fileNum++;
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
        System.out.println("文件夹共有:" + folderNum + ",文件共有:" + fileNum);
        return results;
    }

    public static String getFileType(String currentLine) {
        String[] splits = currentLine.split("=");
        if (splits == null || splits.length != 2) {
            return null;
        }
        String filedTypeStr = splits[0].trim();
        //最后一个空格
        int lastEmptyIndex = filedTypeStr.lastIndexOf(" ");
        if (lastEmptyIndex == -1) {
            return null;
        }
        return filedTypeStr.substring(0, lastEmptyIndex).trim();
    }

    public static String getFileName(String currentLine) {
        String[] splits = currentLine.split("=");
        if (splits == null || splits.length != 2) {
            return null;
        }
        String filedTypeStr = splits[0].trim();
        //最后一个空格
        int lastEmptyIndex = filedTypeStr.lastIndexOf(" ");
        if (lastEmptyIndex == -1) {
            return null;
        }
        return filedTypeStr.substring(lastEmptyIndex).trim();
    }


    public static String getFileDesc(String lastLine) {
        if (StringUtils.isBlank(lastLine) || !lastLine.contains("//")) {
            return null;
        }
        return lastLine.trim().replaceAll("//", "");
    }
}
